/**
 * <pre>
 * Title: 		RaydropService.java
 * Project: 	FullNexus4
 * Type:		com.leoly.fullnexus4.services.RaydropService
 * Author:		255507
 * Create:	 	2013-4-10 下午5:02:57
 * Copyright: 	Copyright (c) 2013
 * Company:		
 * <pre>
 */
package com.leoly.fullnexus4.services;

import java.util.List;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;

import com.leoly.fullnexus4.R;
import com.leoly.fullnexus4.utils.ButtonFactory;
import com.leoly.fullnexus4.utils.EventHandler;
import com.leoly.fullnexus4.utils.RayDropFactory;
import com.leoly.fullnexus4.utils.TopConstants;
import com.leoly.fullnexus4.views.FloatApplication;
import com.leoly.fullnexus4.views.FloatView;
import com.leoly.fullnexus4.vos.IAppObject;

/**
 * <pre>
 * </pre>
 * 
 * @author 255507
 * @version 1.0, 2013-4-10
 */
public class RaydropService extends Service {
	private WindowManager windowManager;

	private WindowManager.LayoutParams windowManagerParams;

	private WindowManager.LayoutParams appParams;

	private Context context;

	private SharedPreferences prefer;

	private FloatView floatView;

	private LinearLayout layout;

	private int raydropAlpha = 80;

	private EventHandler eh = null;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Bundle data = msg.getData();
			boolean wantShow = data.getBoolean(TopConstants.HANDLER_TAG);
			if (wantShow) {
				floatView.setAlpha(raydropAlpha);
			} else {
				floatView.setAlpha(255);
				handler.removeCallbacks(run);
				handler.postDelayed(run, 10000);
			}
		}
	};

	private Runnable run = new Runnable() {
		public void run() {
			Bundle bundle = new Bundle();
			bundle.putBoolean(TopConstants.HANDLER_TAG, true);
			Message msg = new Message();
			msg.setData(bundle);
			handler.sendMessage(msg);
		}
	};

	@Override
	public void onCreate() {
		context = getApplicationContext();
		eh = new EventHandler(context);
		prefer = context.getSharedPreferences(TopConstants.CONFIG_NAME,
				MODE_PRIVATE);
		raydropAlpha = prefer.getInt(TopConstants.RAY_DROP_ALPHA, raydropAlpha);
		windowManager = (WindowManager) getApplicationContext()
				.getSystemService(WINDOW_SERVICE);
		// 设置LayoutParams(全局变量）相关参数
		FloatApplication floatApp = ((FloatApplication) getApplication());
		floatApp.setHandler(handler);
		floatView = new FloatView(floatApp);
		floatView.setImageResource(R.drawable.raydrop); // 这里简单的用自带的icon来做演示
		// 获取WindowManager
		windowManager = (WindowManager) getApplicationContext()
				.getSystemService(Context.WINDOW_SERVICE);
		windowManagerParams = floatApp.getWindowParams();

		windowManagerParams.type = LayoutParams.TYPE_PHONE; // 设置window
															// type
		windowManagerParams.format = PixelFormat.RGBA_8888; // 设置图片格式，效果为背景透明
		// 设置Window flag
		windowManagerParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
				| LayoutParams.FLAG_NOT_FOCUSABLE;
		/*
		 * 注意，flag的值可以为： 下面的flags属性的效果形同“锁定”。 悬浮窗不可触摸，不接受任何事件,同时不影响后面的事件响应。
		 * LayoutParams.FLAG_NOT_TOUCH_MODAL 不影响后面的事件
		 * LayoutParams.FLAG_NOT_FOCUSABLE 不可聚焦 LayoutParams.FLAG_NOT_TOUCHABLE
		 * 不可触摸
		 */
		// 调整悬浮窗口至左上角，便于调整坐标
		windowManagerParams.gravity = Gravity.LEFT | Gravity.TOP;
		// 以屏幕左上角为原点，设置x、y初始值
		windowManagerParams.x = 0;
		windowManagerParams.y = 0;
		// 设置悬浮窗口长宽数据
		windowManagerParams.width = 95;
		windowManagerParams.height = 95;
		floatView.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				eh.sendKeys(KeyEvent.KEYCODE_BACK);
			}
		});

		floatView.setOnMoveListener(new OnMoveListener() {
			public void onMove() {
				floatView.setClickable(false);
				floatView.setVisibility(FloatView.INVISIBLE);
				showSystemBtns();
			}
		});
		// 显示myFloatView图像
		windowManager.addView(floatView, windowManagerParams);
		handler.postDelayed(run, 10000);
	}

	private void showSystemBtns() {
		if (layout != null) {
			appParams.y = 0;
			windowManager.updateViewLayout(layout, appParams);
			return;
		}
		layout = (LinearLayout) LayoutInflater.from(context).inflate(
				R.layout.raygrid, null);
		TableLayout btnTables = (TableLayout) layout
				.findViewById(R.id.btnTable);
		boolean needVibrate = prefer.getBoolean(TopConstants.IS_NEED_VIBRATE,
				false);
		// 根据按键配置获取真实的按钮
		// 获取配置的按键
		int keyHeight = prefer.getInt(TopConstants.KEY_SET_HEIGHT, 10);
		keyHeight = ButtonFactory.getRealValue(keyHeight, 1);
		List<IAppObject> btns = ButtonFactory.getSysButtons(context);
		RayDropFactory factory = RayDropFactory.getInstance(context,
				needVibrate, new ICallBack() {
					public void run() {

					}

					public void hideAllKeys() {
						hideButtons();
					}
				}, eh);

		if (btns.size() == 0) {
			return;
		}
		TableRow tr = null;
		int index = 0;
		for (IAppObject app : btns) {
			if (index % 3 == 0) {
				if (null != tr) {
					btnTables.addView(tr);
				}
				tr = new TableRow(context);
			}
			ImageView iv1 = factory.createItem(app, 40);
			tr.addView(iv1);
			index++;
		}

		if (null != tr) {
			btnTables.addView(tr);
		}
		// 基本信息
		int keyAlpha = prefer.getInt(TopConstants.KEY_SET_ALPHA, 123);
		int keysetColor = prefer.getInt(TopConstants.KEY_SET_COLOR, 0);
		if (keysetColor == 8) {
			layout.setBackgroundResource(R.drawable.shape);
		} else {
			layout.setBackgroundColor(ButtonFactory.getRealColor(keysetColor));
			layout.getBackground().setAlpha(keyAlpha);
		}

		appParams = new WindowManager.LayoutParams();
		// 关键属性
		appParams.gravity = Gravity.CENTER;
		appParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
		appParams.format = 1;
		appParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
		appParams.flags = appParams.flags
				| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
		appParams.flags = appParams.flags
				| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
		appParams.width = 450;
		appParams.height = 450;

		layout.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View view, MotionEvent motionevent) {
				if (motionevent.getAction() == MotionEvent.ACTION_OUTSIDE) {
					hideButtons();
				}
				return false;
			}
		});
		windowManager.addView(layout, appParams);
	}

	private void hideButtons() {
		floatView.setVisibility(View.VISIBLE);
		floatView.setClickable(true);
		appParams.y = -3030;
		windowManager.updateViewLayout(layout, appParams);
	}

	/*
	 * （非 Javadoc）
	 * 
	 * @see android.app.Service#onBind(android.content.Intent)
	 */
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if(null != floatView){
			windowManager.removeViewImmediate(floatView);
		}
		if(null != layout){
			windowManager.removeViewImmediate(layout);
		}
	}
}
